﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace api_blog.Controllers
{
    [Route("api/blog")]
    [ApiController]
    public class BlogController : ControllerBase
    {
        // GET: api/<BlogController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };   
        }

        /// <summary>
        /// 查询博客
        /// </summary>
        /// <param name="parameModel"></param>
        /// <returns></returns>
        [Route("QueryBlog")]
        [HttpPost]
        public async Task<AjaxResult> QueryBlog([FromBody] dynamic parameModel) {
            var task = Task.Run(() => {
                AjaxResult result = new AjaxResult();
                try {
                    string Str = parameModel.str ?? "";
                    string Pid = parameModel.pid ?? "";
                    IEnumerable<dynamic> sort = parameModel.sort;
                    string Html = "";
                    string PidStr = "";
                    if (string.IsNullOrEmpty(Pid)) {
                        Html = PostData("http://192.168.123.161:9200/blog/_pit?keep_alive=1m", "");
                        PidStr = Html.Str2Entity<dynamic>().id;
                    }
                    object PageData = null;
                    if (string.IsNullOrEmpty(Pid)) {
                        if (!string.IsNullOrEmpty(Str.Trim())) {
                            PageData = new {
                                size = 10,
                                query = new {
                                    match = new {
                                        title = new {
                                            query=Str,
                                            operator_ex="and"
                                        }
                                    },
                                },
                                _source = new List<string> { "id", "title", "brief", "createdate" },
                                pit = new {
                                    id = PidStr,
                                    keep_alive = "5m"
                                },
                                sort = new List<object> {
                                    new{
                                        _score=new{
                                            order="desc"
                                        }
                                    }
                                },
                                track_scores=true
                            };
                        }
                        else {
                            PageData = new {
                                size = 10,
                                query = new {
                                    match_all = new {

                                    },
                                },
                                _source = new List<string> { "id", "title", "brief", "createdate" },
                                pit = new {
                                    id = PidStr,
                                    keep_alive = "5m"
                                },
                                sort = new List<object> {
                                    new{
                                        id=new{
                                            order="asc"
                                        }
                                    }
                                }
                            };
                        }
                    }
                    else {
                        if (!string.IsNullOrEmpty(Str)) { 
                            PageData = new {
                                size = 10,
                                query = new {
                                    match = new{
                                        title = new{
                                            query = Str,
                                            operator_ex = "and"
                                        }
                                    },
                                },
                                _source = new List<string> { "id", "title", "brief", "createdate" },
                                pit = new {
                                    id = Pid,
                                    keep_alive = "5m"
                                },
                                sort = new List<object> {
                                    new{
                                        _score=new{
                                            order="desc"
                                        }
                                    }
                                },
                                track_scores=true,
                                search_after = sort
                            };
                        }
                        else { 
                            PageData = new {
                                size = 10,
                                query = new {
                                    match_all = new {
                                        
                                    },
                                },
                                _source = new List<string> { "id", "title", "brief", "createdate" },
                                pit = new {
                                    id = Pid,
                                    keep_alive = "5m"
                                },
                                sort = new List<object> {
                                    new{
                                        id=new{
                                            order="asc"
                                        }
                                    }
                                },
                                search_after = sort
                            };
                        }
                    }

                    Html = PostData("http://192.168.123.161:9200/_search", PageData.ToJson().Replace("operator_ex", "operator"));
                    result.Msg = "ok";
                    result.Data = Html.Str2Entity<dynamic>();
                }
                catch (Exception ex) {
                    result.Msg = ex.Message;
                }
                return result;
            });
            return await task;
        }

        /// <summary>
        /// 根据ID获取文章
        /// </summary>
        /// <param name="parameModel"></param>
        /// <returns></returns>
        [Route("GetBlogById")]
        [HttpPost]
        public async Task<AjaxResult> GetBlogById([FromBody] dynamic parameModel) {
            var task = Task.Run(()=> {
                AjaxResult result = new AjaxResult();
                try{
                    int Id = parameModel.id ?? 0;
                    var PageData = new {
                        query = new {
                            term = new { 
                                id= Id
                            }
                        }
                    };
                    dynamic model=PostData("http://192.168.123.161:9200/blog/_search", PageData.ToJson()).Str2Entity<dynamic>();
                    result.Msg = "ok";
                    result.Data = model;
                }
                catch (Exception ex) {
                    result.Msg = ex.Message;
                }
                return result;
            });
            return await task;
        }

        /// <summary>
        /// 查询最新的
        /// </summary>
        /// <param name="parameModel"></param>
        /// <returns></returns>
        [Route("QueryNewestBlog")]
        [HttpPost]
        public async Task<AjaxResult> QueryNewestBlog([FromBody] dynamic parameModel) {
            var task = Task.Run(()=> {
                AjaxResult result = new AjaxResult();
                try{
                    var PageData = new {
                        size=5,
                        _source= new List<string> { "id","title", "createdate" },
                        sort = new {
                            id = new {
                                order="desc",
                                missing= "_first",
                                unmapped_type= "integer"
                            }
                        }
                    };
                    dynamic model=PostData("http://192.168.123.161:9200/blog/_search", PageData.ToJson()).Str2Entity<dynamic>();
                    result.Data = model;
                    result.Msg = "ok";
                }
                catch (Exception ex) {
                    result.Msg = ex.Message;
                }
                return result;
            });
            return await task;
        }

        [Route("QueryHostestBlog")]
        [HttpPost]
        public async Task<AjaxResult> QueryHostestBlog([FromBody] dynamic parameModel) {
            var task = Task.Run(()=> {
                AjaxResult result = new AjaxResult();
                try{
                    var PageData = new {
                        size=5,
                        _source = new List<string> { "id","title", "createdate" },
                        sort = new {
                            id = new {
                                order="asc",
                                missing= "_first",
                                unmapped_type= "integer"
                            }
                        }
                    };
                    dynamic model=PostData("http://192.168.123.161:9200/blog/_search", PageData.ToJson()).Str2Entity<dynamic>();
                    result.Data = model;
                    result.Msg = "ok";
                }
                catch (Exception ex) {
                    result.Msg = ex.Message;
                }
                return result;
            });
            return await task;
        }

        /// <summary>
        ///   http://es.node1.com:9200/blog/_doc
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        private string PostData(string url,string obj){
            using (HttpHelper http = new HttpHelper()){
                HttpItem item = new HttpItem();
                item.URL = url;
                item.Method = "POST";
                item.ContentType = "application/json; charset=UTF-8";
                item.Header.Add("Accept-Encoding", "gzip, deflate");
                item.Header.Add("Upgrade-Insecure-Requests", "1");
                item.Header.Add("Authorization", $"Basic {"elastic:elastic".ToBase64()}");
                item.PostEncoding = System.Text.Encoding.UTF8;
                item.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; Tablet PC 2.0; TCO_20150304085044)";
                item.PostDataType = PostDataType.String;
                item.PostEncoding = System.Text.Encoding.UTF8;
                if (!string.IsNullOrEmpty(obj)) {
                    item.Postdata = obj;
                }
                HttpResult result = http.GetHtml(item);
                string Html = result.Html;
                return Html;
            }
        }


        // GET api/<BlogController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<BlogController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<BlogController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<BlogController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
